/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.cloud.nacos;

import com.alibaba.cloud.nacos.client.BootPropertySourceLocator;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 扩展NacosPropertySourceLocator，加载nacos中配置文件及配置项，并存储至环境变量中
 * 注：当配置文件存在相同属性时，将通过配置文件名+配置项名称方式合并配置，如：deploySystem-plm.yml 、deploySystem-gateway.yml 中均存在 runtimeclasses 配置项，
 *  * 则环境变量中会存入 deploySystem-plm.runtimeclasses =1 , deploySystem-gateway.runtimeclasses =2
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigBootstrapConfiguration {

	@Value("${ibiz.runtime.config.enableBootServiceHub:false}")
	private boolean enableBootServiceHub;
	@Value("${ibiz.runtime.config.bootServiceHubFile:}")
	private String fileName;
	@Value("${ibiz.runtime.config.bootServiceHubFileExtension:yaml}")
	private String fileExtension;

	@Bean
	@ConditionalOnMissingBean
	public NacosConfigProperties nacosConfigProperties() {
		return new NacosConfigProperties();
	}

	@Bean
	@ConditionalOnMissingBean
	public NacosConfigManager nacosConfigManager(
			NacosConfigProperties nacosConfigProperties) {
		return new NacosConfigManager(nacosConfigProperties);
	}

	@Bean
	public NacosPropertySourceLocator nacosPropertySourceLocator(
			NacosConfigManager nacosConfigManager) {
		if(enableBootServiceHub){
			BootPropertySourceLocator propertySourceLocator = new BootPropertySourceLocator(nacosConfigManager);
			propertySourceLocator.setFileName(fileName);
			propertySourceLocator.setFileExtension(fileExtension);
			return propertySourceLocator;
		}
		else
			return new NacosPropertySourceLocator(nacosConfigManager);
	}

}
